package com.hxzy.util;

import javax.validation.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/1 14:46
 */
public class BeanValidatorUtil {

/**
 * 验证数据就去
 * @param clazz
 * @param obj
 * @param <T>
 * @return Set.size()>0有错误
 */
public static <T> Set<String> validator(Class<T> clazz,Object obj){
        Set<String> errorSet=new HashSet<>();

        //创建验证器工厂
        ValidatorFactory validatorFactory= Validation.buildDefaultValidatorFactory();
        Validator validator= validatorFactory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations=validator.validate((T)obj);
        if (constraintViolations.isEmpty()){
            System.out.println("验证成功");
        }else {
            //显示第一个错误
            ConstraintViolation<T> next = constraintViolations.iterator().next();
            errorSet.add(next.getMessage());
        }
        return errorSet;
    }

}
